package com.motu.monstercity.server.login.verticle;

import com.motu.vertx.module.utility.toolset.Tool;
import com.motu.vertx.module.utility.webtool.BaseWebHandler;
import io.vertx.core.AbstractVerticle;
import io.vertx.core.AsyncResult;
import io.vertx.core.Handler;
import io.vertx.core.Promise;
import io.vertx.core.http.HttpMethod;
import io.vertx.core.http.HttpServer;
import io.vertx.core.json.JsonObject;
import io.vertx.ext.web.Router;
import io.vertx.ext.web.RoutingContext;
import io.vertx.ext.web.handler.CorsHandler;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.HashSet;
import java.util.Set;

public class GetipVerticle extends AbstractVerticle {

    private static final Logger logger = LoggerFactory.getLogger(GetipVerticle.class);

    @Override
    public void start(Promise<Void> future) {

        startWeb(httpServer -> {
            if (httpServer.failed()) {
                logger.error(" ### GetipVerticle startWeb fail !!!");
                httpServer.cause().printStackTrace();
                future.fail(httpServer.cause());
            } else {
                logger.info("----===listen port " + httpServer.result().actualPort());
                future.complete();
            }
        });

    }

    public void startWeb(Handler<AsyncResult<HttpServer>> nextHandler) {

        logger.info(">>>>>>>>>>>>>>> startWeb");
        Router router = Router.router(vertx);
        Set<String> allowHeaders = new HashSet<>();
        allowHeaders.add("x-requested-with");
        allowHeaders.add("Access-Control-Allow-Origin");
        allowHeaders.add("origin");
        allowHeaders.add("Content-Type");
        allowHeaders.add("accept");
        router.route().handler(CorsHandler.create("*").allowedHeaders(allowHeaders).allowedMethod(HttpMethod.GET));
        router.route("/").handler(routingContext -> {
            routingContext.response().setStatusCode(200).setStatusMessage("OK").end("GetipVerticle service is running!!");
        });

        router.get("/myip/*").handler(this::doGetIp);


        vertx.createHttpServer().requestHandler(router).listen(config().getInteger("getip-http-port"),
                config().getString("host-name"), nextHandler::handle);

    }

    public void doGetIp(RoutingContext routingContext) {
        String ip = Tool.getClientIp(routingContext);
        String countryCode = Tool.getIpCountry(routingContext);
        JsonObject obj = new JsonObject().put("ip", ip).put("country", countryCode);
        routingContext.response().end(obj.toString());
    }

}
